package com.qnbc.mystery.controller.admin;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qnbc.mystery.config.AliPayConfig;
import com.qnbc.mystery.core.controller.BaseController;
import com.qnbc.mystery.core.domain.AjaxResult;
import com.qnbc.mystery.core.utils.poi.ExcelUtil;
import com.qnbc.mystery.pojo.domain.FoodOrder;
import com.qnbc.mystery.pojo.domain.OrderDetail;
import com.qnbc.mystery.pojo.dto.GetOrderCount;
import com.qnbc.mystery.service.IFoodOrderService;
import com.qnbc.mystery.service.IOrderDetailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * 订单管理
 *
 * @author guzj
 * @date 2023-12-27
 */
@Slf4j
@RestController
@RequestMapping("/order")
@Api(tags = "后台订单管理")
public class OrderController extends BaseController {
    @Autowired
    private IFoodOrderService orderService;
    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private AliPayConfig aliPayConfig;


    //统计
    @GetMapping("/getCount")
    public AjaxResult getCount() {
        List<GetOrderCount> getOrderCountList = new ArrayList<>();

        List<FoodOrder> list = orderService.list();
        Map<String, Integer> map = new HashMap<>();
        for (FoodOrder dateListEntry : list) {
            String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date(String.valueOf(dateListEntry.getCreatedTime())));
            map.merge(format, 1, (a, b) -> (Integer) a + b);
        }


        for (FoodOrder foodOrder : list) {
            String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date(String.valueOf(foodOrder.getCreatedTime())));
            GetOrderCount getOrderCount = new GetOrderCount();
            getOrderCount.setDate(format);
            getOrderCount.setOrderAmount(foodOrder.getTotalprice());
            getOrderCount.setOrderCount(String.valueOf(map.get(format)));
            getOrderCountList.add(getOrderCount);
        }

        ArrayList<GetOrderCount> collect1 = getOrderCountList.stream()
                .collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(
                                s -> String.valueOf(s.getDate())))), ArrayList::new));

        List<GetOrderCount> collect = collect1.stream()
                .sorted(Comparator.comparing(GetOrderCount::getDate))
                .collect(Collectors.toList());
        return AjaxResult.success(collect);
    }

    /**
     * 订单发货
     */
    @ApiOperation("订单发货")
    @GetMapping("/sendGoods")
    public AjaxResult sendGoods(FoodOrder order) {
        //订单更新为已发货, 并记录物流单号
        return toAjax(orderService.updateFoodOrder(order));
    }

    /**
     * 查询订单管理列表
     */
    @GetMapping("/list")
    public AjaxResult list(FoodOrder order) {
        PageHelper.startPage(order.getPageNum(), order.getPageSize());

        List<FoodOrder> orderList = orderService.selectFoodOrderList(order);
        for (FoodOrder foodOrder : orderList) {
            LambdaQueryWrapper<OrderDetail> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(OrderDetail::getMid, foodOrder.getId());
            List<OrderDetail> one = orderDetailService.list(queryWrapper);
            if (CollectionUtils.isEmpty(one)) {
                continue;
            }
            List<OrderDetail> list = new ArrayList<>(one);
            foodOrder.setGoods(list);
        }
        return AjaxResult.success(new PageInfo<FoodOrder>(orderList));
    }

    /**
     * 导出订单管理列表
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, FoodOrder order) {
        List<FoodOrder> list = orderService.selectFoodOrderList(order);
        ExcelUtil<FoodOrder> util = new ExcelUtil<FoodOrder>(FoodOrder.class);
        util.exportExcel(response, list, "订单管理数据");
    }

    /**
     * 获取订单管理详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(orderService.selectOrderById(id));
    }

    /**
     * 修改订单管理
     */
    @PutMapping
    public AjaxResult edit(@RequestBody FoodOrder order) {
        return toAjax(orderService.updateFoodOrder(order));
    }

    /**
     * 删除订单管理
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(orderService.deleteFoodOrderByIds(ids));
    }

}
